﻿using System.Collections;

namespace CSharPro._1023;

public class Demo
{
    public void TestPrint()
    {
        int[] arr1 = new int[5];
        arr1[0] = 1;
        arr1[1] = 2;
        arr1[2] = 3;
        arr1[3] = 4;
        for (int i = 0; i < arr1.Length; i++)
        {
            Console.Write(arr1[i] + "\t");
        }

        String[] arr2 = new string[5];
        arr2[0] = "Hello";
        arr2[1] = "World";
        arr2[2] = "haha";
        for (int i = 0; i < arr2.Length; i++)
        {
            Console.Write(arr2[i] + "\t");
        }

        int[] arr3 = { 1, 2, 3, 4, 5, 6 };
        Console.WriteLine(arr3[4]);

        int[,] arr4 = new int[3, 3];
        arr4[0, 0] = 1;
        arr4[1, 1] = 2;
        arr4[2, 2] = 3;

        int[,] arr5 =
        {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        int[] arr6 = { 4, 55, 33, 56, 77 };
        Array.Sort(arr6);
        Array.Reverse(arr6);
        Console.WriteLine();
        foreach (var i in arr6)
        {
            Console.Write(i + "\t");
        }

        //.var
        ArrayList list = new ArrayList();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Add("abd");
        Console.WriteLine(list.Count);
        Console.WriteLine();

        //System.InvalidCastException
        //Unable to cast object of type 'System.String' to type 'System.Int32'
        foreach (object i in list)
        {
            Console.Write(i + "\t");
        }

        list.Remove(33);
        Console.WriteLine();

        Hashtable ht = new Hashtable();
        ht.Add("name", "zhangsan");
        ht.Add("age", "18");
        ht.Add("sex", "mail");
        foreach (DictionaryEntry entry in ht)
        {
            Console.Write(entry.Key + "\t" + entry.Value + "\t");
            Console.WriteLine();
        }

        ht.Remove(key: "age");
    }

    public static void BubbleSort(int[] array)
    {
        if (array == null || array.Length < 2)
            return;

        int length = array.Length;
        bool isSwapped;
        for (int i = 0; i < length - 1; i++)
        {
            isSwapped = false;
            
            for (int j = 0; j < length - 1 - i; j++)
            {
                
                if (array[j] > array[j + 1])
                {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    isSwapped = true; 
                }
            }

            // 若本轮未发生交换，说明数组已有序，提前退出
            if (!isSwapped)
                break;
        }
    }
}